package xdu.lz.stage2_design_pattern.chapter8_guarded_suspension_pattern;

import java.util.Random;

public class ServerThread extends Thread {

    private final RequestQueue queue;

    private static final Random random = new Random(System.currentTimeMillis());;

    private volatile boolean flag = true;

    public ServerThread(RequestQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (flag){
            //如果队列为空，会被wait住。
            Request request = queue.getRequest();
            //如果request == null 说明close方法中interrupt打断了getRequest的wait
            if (request == null){
                System.out.println("request == null");
                continue;
            }
            System.out.println("server -> "+request.getValue());
            try {
                Thread.sleep(random.nextInt(10));
            } catch (InterruptedException e) {
                System.out.println("被中断，线程死亡");
                return;
            }
        }
    }

    public void close(){
        this.flag = false;
        //之所以加interrupt是因为在拿队列中的元素时，
        //有可能被wait住，那么就没机会判断flag
        //打断当前线程this
        this.interrupt();
    }
}
